package com.yj.springbootstudy.mulThread.imooc.juctools;

import java.util.concurrent.atomic.AtomicInteger;

/*
 * 使用AtomicInteger 原子类实现售票案例
 */
public class AtomicIntegerTest {

    static java.util.concurrent.atomic.AtomicInteger atomicInteger = new AtomicInteger(10);

    public static void main(String[] args) {
        for (int i = 0; i < 3 ; i++) {
            TicketOffice ticketOffice = new TicketOffice(atomicInteger, i + "");
            new Thread(ticketOffice).start();
        }
    }

}

class TicketOffice implements Runnable{
    private AtomicInteger count;
    private String name;

    public TicketOffice(AtomicInteger count,String name){
        this.count = count;
        this.name = name;
    }

    @Override
    public void run() {
        while (true){
            if (count.get() < 1){
                System.out.println("当前票已经售完");
                return;
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            int result = count.decrementAndGet();
            if (result>0){
                System.out.println("当前"+name+"已出票，剩余："+result+"张票");
            }
        }
    }
}